<?php
/**
 * Created by PhpStorm.
 * User: l-ht
 * Date: 2018/10/28
 * Time: 09:48
 */

namespace app\index\controller;

use app\index\model\Share;
use think\Loader;
use think\Request;
use app\index\model\User;
use app\index\model\Thread;
class Grant extends Base
{
    protected $_user;

    public function __construct(User $user)
    {
        $this->_user = $user;
    }

    //openid 授权
    public function getOpenid(Request $request)
    {

        $data   = $request->only(["code","userInfo"]);

        $arr = $this->getOpenMsg($data['code']);

        if (isset($arr['openid'])) {

            $session_key = $arr['session_key'];
            session('session_key',$session_key);

            $user = $this->_user->where('openid',$arr['openid'])->find();
            $userInfo = json_decode($data['userInfo'],true);
            if (!$user) {

                $this->_user = new User();
                $this->_user->openid   = $arr['openid'];
                $this->_user->nickname = $userInfo['nickName'];
                $this->_user->city     = $userInfo['city'];
                $this->_user->sex      = $userInfo['gender'];
                $this->_user->avatar   = $userInfo['avatarUrl'];
                $this->_user->created_at = date("Y-m-d H:i:s",time());
                $this->_user->save();
                $uid = $this->_user->id;

            }else{
                //$this->_user->where('id',$user['id'])->update(['avatar' => $userInfo['avatarUrl']]);
                $uid = $user['id'];
            }

            return $this->_toSuccess(['uid' => $uid ,'msg' => '登录成功']);
        }else{
            return $this->_toError(['msg' => $arr['errmsg']]);
        }
    }


    //获取用户详情
    public function getOpenMsg($code)
    {
        $appId  = config()["wx"]["appid"];
        $secret = config()["wx"]["secret"];

        $url   = "https://api.weixin.qq.com/sns/jscode2session?appid={$appId}&secret={$secret}&js_code={$code}&grant_type=authorization_code";
        $grant = file_get_contents($url);
        $arr   = json_decode($grant,true);

        return $arr;
    }

    //获取账户信息
    public function account()
    {
        $uid  = input("uid");
		$city = input("city");
        $data = $this->_user->where('id',$uid)->find();
		if($data['city']==""){
			$data['city'] = $city;
		}
		if($data['phone']=="-1"){
			$data['phone'] = "";
		}
		$data['tNum'] = Thread::where('authorid',$uid)->count();
		$data['shareNum'] = Share::where("uid",$uid)->count();
        return $this->_toSuccess($data);
    }

    //授权手机号
    public function phone(Request $request)
    {

        require '../extend/wxBizDataCrypt.php';
        //Loader::import('wxBizDataCrypt');
        if (input("code") == null || input("code") == 'null') {
            $session_key = session('session_key');
        }else{
            $arr = $this->getOpenMsg(input("code"));
            $session_key = $arr['session_key'];
        }

        $appId = config()["wx"]["appid"];
        $pc = new \WXBizDataCrypt($appId,$session_key);
        $errCode = $pc->decryptData($request->get('enc'),$request->get('iv'),$data);
//        dump($errCode);die;
        if ($errCode == 0) {

            $phoneNumArr = json_decode($data,true);
            $phoneNumArr['phoneNumber'] && $this->_user->where('id',$request->get('uid'))->update(['phone' => $phoneNumArr['phoneNumber']]);

            return $this->_toSuccess(['msg' => '手机号授权成功']);

        } else {
            return $this->_toError(['msg' => '手机号授权失败']);
        }

    }

    //修改用户名
    public function savename()
    {
        $uid  = input("uid");
		$nikename  = input("nickname");
		$res = $this->_user->where('id',$uid)->update(['nickname' => $nikename]);
        if($res){
			return $this->_toSuccess(['uid' => $uid ,'msg' => '修改成功']);
		}else{
			return $this->_toError(['msg' => '修改失败']);
		}
    }	
    //修改性别
    public function savesex()
    {
        $uid  = input("uid");
		$sex  = input("sex");
		$res = $this->_user->where('id',$uid)->update(['sex' => $sex]);
        if($res){
			return $this->_toSuccess(['uid' => $uid ,'msg' => '修改成功']);
		}else{
			return $this->_toError(['msg' => '修改失败']);
		}
    }	

}